import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {Badge, Button, Card, Divider, Form, Input, InputNumber, Modal, Radio,} from 'antd';
import TableList from '@/components/TableList';
import styles from '../search.less';
import {ruleP} from '@/utils/rule';
import {decode, encode} from '@/utils/AesUtil';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
const statusMap = ['', 'success', 'error'];
const status = ['', '启用', '禁用'];

const FormItem = Form.Item;
const formLayout = {
  labelCol: {span: 5},
  wrapperCol: {span: 18},
};
const CreateForm = Form.create()(props => {
  const {modalVisible, form, addDataFn, updateFn, handleModalVisible, text, testEmail} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text)
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  const testEmailF = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // form.resetFields();
      testEmail(fieldsValue)
    });
  };

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑邮箱' : '新增邮箱'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="邮件服务器名称">
        {form.getFieldDecorator('emailServerName', {
          rules: [{required: true, message: '邮件服务器名称不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text && text.emailServerName || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem {...formLayout} label="邮件服务器编码">
        {form.getFieldDecorator('emailServerCode', {
          rules: [{required: true, message: '邮件服务器编码不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text && text.emailServerCode || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem {...formLayout} label="Email地址">
        {form.getFieldDecorator('address', {
          rules: [{required: true, message: 'Email地址不能为空'},
            {pattern: new RegExp(ruleP(9)[0], 'g'), message: ruleP(9)[1]}],
          initialValue: text && text.address || ''
        })(<Input placeholder="例：test@123.com"/>)}
      </FormItem>
      <FormItem {...formLayout} label="密码">
        {form.getFieldDecorator('password', {
          rules: [{required: true, message: '密码不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: decode(text && text.password) || ''
        })(<Input type="password" placeholder="请输入"/>)}
      </FormItem>
      <FormItem {...formLayout} label="显示名称">
        {form.getFieldDecorator('showName', {
          rules: [{required: true, message: '显示名称不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text && text.showName || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem {...formLayout} label="发件服务器IP">
        {form.getFieldDecorator('sendingIp', {
          rules: [{required: true, message: '发件服务器IP不能为空'},
            ],
          initialValue: text && text.sendingIp || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem {...formLayout} label="端口号">
        {form.getFieldDecorator('port', {
          rules: [{required: true, message: '端口号不能为空'}],
          initialValue: text && text.port || ''
        })(<InputNumber placeholder="请输入" min={0} max={65535} style={{width: '100%'}}/>)}
      </FormItem>
      <FormItem {...formLayout} label="SSL加密">
        {form.getFieldDecorator('sslFlag', {
          initialValue: text && text.sslFlag,
          rules: [{required: true, message: 'SSL加密不能为空'}],
        })(<Radio.Group>
          <Radio value={0}>是</Radio>
          <Radio value={1}>否</Radio>
        </Radio.Group>)}
      </FormItem>
      <FormItem {...formLayout} label="状态">
        {form.getFieldDecorator('state', {
          initialValue: text && text.state,
          rules: [{required: true, message: '状态不能为空'}],
        })(<Radio.Group>
          <Radio value={1}>启用</Radio>
          <Radio value={2}>禁用</Radio>
        </Radio.Group>)}
      </FormItem>
      <FormItem {...formLayout} label="测试邮箱">
        {form.getFieldDecorator('textEmail', {
          rules: [{required: false, message: '测试邮箱不能为空'}
            , {max: 60, message: "字符长度不能超过60"},

            {pattern: new RegExp(ruleP(9)[0], 'g'), message: ruleP(9)[1]}],
          initialValue: text && text.textEmail || ''
        })(<Input placeholder="接受测试邮件的邮箱地址"/>
        )}
      </FormItem>
      <Button type="primary" onClick={testEmailF} style={{marginLeft: '123px'}}>
        发送邮件
      </Button>
    </Modal>
  );
});

@Form.create()
@connect(({mailboxC, loading}) => ({
  mailboxC,
  loading: loading.models.mailboxC,
}))
@Form.create()
class MailboxC extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    text: {},
  };

  columns = [
    {
      title: '邮件服务器名称',
      dataIndex: 'emailServerName',
    },

    {
      title: '邮件服务器编码',
      dataIndex: 'emailServerCode',
    },

    {
      title: 'Email地址',
      dataIndex: 'address',
    },

    {
      title: '显示名称',
      dataIndex: 'showName',
    },

    {
      title: '发件服务器IP',
      dataIndex: 'sendingIp',
    },

    {
      title: '端口',
      dataIndex: 'port',
    },

    {
      title: '状态',
      dataIndex: 'state',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },

    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          <Divider type="vertical"/>
          <a onClick={() => this.deleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];

 async componentDidMount() {
    this.pageList();
    // 先获取秘钥
    await decode('123')
  }

  // 分页查询列表
  pageList(data, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'mailboxC/queryList',
      payload: values,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };
  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleThisRowDelete = (id) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'mailboxC/remove',
      payload: {id},
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            selectedRows: [],
          });
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text
    });
  };

  // 更新接口
  updateFn =async (fields, text) => {
    const {dispatch} = this.props;
    const params = {
      id: text.id,
      emailServerName: fields.emailServerName,
      emailServerCode: fields.emailServerCode,
      address: fields.address,
      password:await encode(fields.password),
      showName: fields.showName,
      sendingIp: fields.sendingIp,
      port: fields.port,
      sslFlag: fields.sslFlag,
      state: fields.state
    }
    dispatch({
      type: 'mailboxC/update',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          this.handleModalVisible();
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };

  // 增加接口
  addDataFn =async (fields) => {
    const {dispatch} = this.props;
    const params = {
      emailServerName: fields.emailServerName,
      emailServerCode: fields.emailServerCode,
      address: fields.address,
      password:await encode(fields.password),
      showName: fields.showName,
      sendingIp: fields.sendingIp,
      port: fields.port,
      sslFlag: fields.sslFlag,
      state: fields.state
    }
    dispatch({
      type: 'mailboxC/add',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          this.handleModalVisible();
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };

  // 测试邮箱
  testEmail =async (fields) => {
    const {dispatch} = this.props;
    const params = {
      emailServerName: fields.emailServerName,
      emailServerCode: fields.emailServerCode,
      address: fields.address,
      password:await encode(fields.password),
      showName: fields.showName,
      sendingIp: fields.sendingIp,
      port: fields.port,
      sslFlag: fields.sslFlag,
      state: fields.state,
      textEmail: fields.textEmail,
    }
    dispatch({
      type: 'mailboxC/testmail',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };

  render() {
    const {
      mailboxC: {data},
      loading,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      editFormValues,
      text
    } = this.state;

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      testEmail: this.testEmail,
    };
    return (
      <PageHeaderWrapper title="邮箱配置">
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        <div className={styles.tableList}>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
        </div>
      </Card>
      </PageHeaderWrapper>
    );
  }
}

export default MailboxC;
